import axios from 'axios'
import Vrouter from "@/router" // 路由直接引入对象
import { ElMessage } from 'element-plus'
import { getToken } from './auth'
const router = Vrouter
// create an axios instance
const service = axios.create({
	baseURL: "http://api.xszhg.cn", //线上地址
	//baseURL: "http://219.153.12.166:84",
	// baseURL: "http://192.168.0.25:3231", //测试
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 20000 // 请求超时
})
// request interceptor
service.interceptors.request.use(
  config => {
    if (getToken()) {
      // 判断是否有headers
      if(config&&config?.headers){
        config.headers['token'] = getToken()
      }
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)
// 返回报错截栏 根据后台提供报错处理
service.interceptors.response.use(
  response => {
		const res = response.data
		// 请求失败跳转到指定页面
		if (res.result == 9) {
			router.push('/about')
			return
		}
		const msg = res.message || '请求失败'
		if (res.result == 0 || res.result != 1) {
			ElMessage({
        message: msg,
        type: 'error',
        duration: 2000
			})
			return
		}
		if (res.result == 1) {
			return res
		}
  },
  error => {
    ElMessage({
      message: error.message,
      type: 'error',
      duration: 2000
    })
    return Promise.reject(error)
  }
)
export default service